package com.abel.main.publish.subscribe;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class Publish {

    public static void main(String[] args) {
        sendMessage("你好吗！");
    }

    private static void sendMessage(String data) {
        ConnectionFactory factory = null;
        Connection connection = null;
        Session session = null;
        Destination destination = null;
        MessageProducer producer = null;
        Message message = null;

        try {
            factory = new ActiveMQConnectionFactory("admin", "amdin", "tcp://192.168.26.50:61616");
            connection = factory.createConnection();
            connection.start();

            session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
            destination = session.createTopic("pub-sub");
            producer = session.createProducer(destination);
            message = session.createTextMessage(data);
            producer.send(message);
            System.out.println("消息已发送");
        } catch (JMSException e) {
            e.printStackTrace();
        } finally {
            if (producer != null) {
                try {
                    producer.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
            if (session != null) {
                try {
                    session.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
